package org.example.day11;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 4.1.13.1 lock.lockInterruptibly()
 *      ①lock.lock()时，无论线程是否被中断，线程都将获得锁.
 *      ②lock.lockInterruptibly()时，如果线程未被中断，则获取锁定，如果线程被中断，则报出异常.
 **/
public class MyThread15 {
    public ReentrantLock lock = new ReentrantLock();
    private Condition condition = lock.newCondition();

    public void waitMethod() {
        try {
//            lock.lock();
            lock.lockInterruptibly();
            System.out.println("lock begin, ThreadName = " + Thread.currentThread().getName());
            //长任务
            for (int i = 0; i < Integer.MAX_VALUE/10; i++) {
                String newString = new String();
                Math.random();
            }
            System.out.println("lock end, ThreadName = " + Thread.currentThread().getName());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            if (lock.isHeldByCurrentThread()) {
                lock.unlock();
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        final MyThread15 m15 = new MyThread15();
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                m15.waitMethod();
            }
        };
        Thread ta = new Thread(runnable);
        ta.setName("A");
        ta.start();
        Thread.sleep(500);

        Thread tb = new Thread(runnable);
        tb.setName("B");
        tb.start();

        tb.interrupt(); //线程B在等待lock的过程中被赋予中断标记，不影响继续执行.
        System.out.println("main end");
    }
}
